package demo2;

import java.util.ArrayList;
import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        int[] array1 = {1,2,3};
        int[] array2 = {8,2,2,3,8};
        ArrayList<Integer> nums1 = new ArrayList<>();
        ArrayList<Integer> nums2 = new ArrayList<>();

        for (int i = 0; i < array1.length; i++) {
            nums1.add(array1[i]);
        }
        for (int i = 0; i < array2.length; i++) {
            nums2.add(array2[i]);
        }
        System.out.println(intersection(nums1, nums2).toString());
    }
    public static ArrayList<Integer> intersection (ArrayList<Integer> nums1, ArrayList<Integer> nums2) {
        if (nums2.size()>nums1.size()){
            ArrayList<Integer> tmp = nums1;
            nums1 = nums2;
            nums2 = tmp;
        }

        //将较小的列表存入HashSet
        HashSet<Integer> numSet = new HashSet<>(nums2);
        ArrayList<Integer> result = new ArrayList<>();
        for (Integer num : nums1) {
            if (numSet.contains(num)){
                result.add(num);
                numSet.remove(num);
            }
        }
        return result;

    }
}
